
//Global thingies
var RenderProperties = new Array();
var RunArray = new Array();
//var default_url = "runs.xml";
//var default_url = "http://lca2.ucsd.edu/xml/members/dcollins/runs/a9061bd2-1bcf-49b0-ba7d-b476838db10a"
var default_url = "http://lca.ucsd.edu/xml/members/dcollins/runs/";
var dbg = 2;
//var default_url = "parse_output2_short.xml";
//var default_url = "parse_output2.xml";
//var default_url = "parse_output2_hax.xml";
//var default_url = "parse_output.xml";
//var default_url = "test_runs.xml";
//var default_url = "test_runs2.xml";
//var default_url = "test_runs3.xml";
//var default_url = "http://localhost/~davidcollins/Research/Work/Notes/Working/methods.xml"

function start_browser(){
    
    //alertToMonitor('Loaded window.');
    //AssembleMonitorWindow();
    
    setXMLParseMethod('UsePreFilled');
    //setXMLParseMethod('ExamineXML');
    
    //setTagTreeMethod('AsTableColumn');
    setTagTreeMethod('TreeMethod1');
    
    AssembleQueryBox();
    query_database();
    //query_database calls parse_xml as the state change funciton.
    //Upon success, parse_xml calls:
    //  1.) generateRunArrayFromXML();
    //  2.) fillColumnSwitch();
    //  2.) Render();

}

function fillColumnSwitch(){

    //For now, we'll assume that all runs are the same, and examine
    //only the first

    ManipulationBox = document.getElementById('ListContent');
    if( ! ManipulationBox){
	alertToMonitor('Error: No ManipulationBox found.');
	return;
    }
    var RowCounter = 0;
    var nColumns = 4;

    ManipulationBox.innerHTML = "";
    table = document.createElement('table');
    table.setAttribute('border',2);
    body=document.createElement('tbody');

    if( returnXMLParseMethod() == "ExamineXML"){
	FillRenderPropertiesSimple(RunArray);
    }else if ( returnXMLParseMethod() == "UsePreFilled" ){
	FillRenderPropertiesPreFilled();
    }else{
	alertToMonitor('Badly Defined XML Parse Method');
    }
    var RowToAppend = true;
    for(var i=0; i<RenderProperties.length;i++){
	if( RowCounter++ % nColumns == 0 ){
	    var row = document.createElement('tr');
	    RowToAppend = true;
	}
	var cell = document.createElement('td');
	var nodeText = RenderProperties[i].TagText;
	var text = document.createTextNode(nodeText);
	cell.appendChild(text);
	cell.column_name = RenderProperties[i].TagName;
	cell.onclick = toggleRenderStatus;
	cell.style.backgroundColor = ( RenderProperties[i].RenderStatus == "Yes" ) ? 'white' : 'grey';

	cell.style.cursor = 'pointer';
	row.appendChild(cell);
	if( RowCounter % nColumns == nColumns-1 ){
	    body.appendChild(row);
	    RowToAppend = false;
	}
    }
    //Pick up leftovers.
    if( RowToAppend = true ){
	body.appendChild(row);
    }
    table.appendChild(body);
    ManipulationBox.appendChild(table);
    
    button=document.createElement('input');
    button.type = "button";
    button.onclick = Render;
    button.value = "Redraw";
    ManipulationBox.appendChild(button);

    for(var i=0;i<2;i++){
	resizeBox('ManipulationBox',
		  button.clientHeight + button.offsetTop + 3,
		  table.clientWidth+3);
    }

}

function FillRenderPropertiesPreFilled(){

    RenderProperties.splice(0,RenderProperties.length);
    
    //function RenderPropertiesObject(TagName, TagText,RenderStatus, RenderMethod,funcArgs);
    RenderProperties = 
	[ new RenderPropertiesObject('id','id','No','Simple'),
	  new RenderPropertiesObject('TagList',null,'No','SubTable',
				     {'TagName':'Tag','TagAttr':null,'floatTable':true}),  
	  new RenderPropertiesObject('UserFieldList',null,'Yes','SubTable', 
				     {'TagName':'UserField','TagAttr':'name','floatTable':true}),
	  new RenderPropertiesObject("Name","Name", "Yes", "Simple"),
	  new RenderPropertiesObject('Description',null,'Yes','Simple'),
	  new RenderPropertiesObject("Computer","Computer", "No", "Simple"),
	  new RenderPropertiesObject('Comments',null,'No','Simple'),
	  new RenderPropertiesObject('ToDo',null,'No','Simple'),
	  new RenderPropertiesObject('Successful',null,'No','Simple'),
	  new RenderPropertiesObject('JobID',null,'Yes','Simple'),
	  new RenderPropertiesObject('SubmitTime',null,'Yes','Simple'),
	  new RenderPropertiesObject('StartTime',null,'Yes','Simple'),
	  new RenderPropertiesObject('EndTime',null,'Yes','Simple'),
	  new RenderPropertiesObject('ParameterList',null,'No','SubTable'),
	  new RenderPropertiesObject('Program',null,'No','Simple'),
	  new RenderPropertiesObject('User',null,'No','Simple'),
	  new RenderPropertiesObject('JobName',null,'No','Simple'),
	  new RenderPropertiesObject('Nodes',null,'No','Simple'),
	  new RenderPropertiesObject('TasksPerNode',null,'No','Simple'),
	  new RenderPropertiesObject('Queue',null,'No','Simple'),
	  new RenderPropertiesObject('Account',null,'No','Simple'),
	];
    
}    
function FillRenderPropertiesSimple(RunArray){
    //Erase current ElementList.
    //There has to be a better way than this, but I'm pretty new at Javascript.
    Run0 = RunArray[0];
    RenderProperties.splice(0,RenderProperties.length);
    
    for(var i=0; i<Run0.xml.childNodes.length; i++){
	if( Run0.xml.childNodes[i].nodeType != 1 ) continue;
	var nodeName = Run0.xml.childNodes[i].nodeName;
	var nodeText = nodeName;
	RenderProperties.push( new RenderPropertiesObject(nodeName, nodeName,"Yes", "Simple") );
	
    }
    //for( i=0; i<RenderProperties.length;i++){
    //alertToMonitor('aaa '+RenderProperties[i].TagName);
    //}
}    
//needs to become part of the object.
function propertyIndexForTag(TagName){
    for(var i=0;i<RenderProperties.length;i++){
	if( RenderProperties[i].TagName == TagName ) return i;
    }
    return -1;
}
function toggleRenderStatus(){

    index = propertyIndexForTag(this.column_name);
    //alertToMonitor('arse' + index);
    if( index == -1 ) return;
    if( RenderProperties[index].RenderStatus == "Yes" ){
	RenderProperties[index].RenderStatus = "No";
	this.style.backgroundColor = 'grey';
    }else{
	RenderProperties[index].RenderStatus = "Yes";
	this.style.backgroundColor = 'white';
    }

}

function ObtainRenderList(){
    ListToRender = new Array();
    for(var i=0;i<RenderProperties.length; i++)
	if(RenderProperties[i].RenderStatus == "Yes" )
	    ListToRender.push( RenderProperties[i] );
    
    return ListToRender;
}
var timesRendered=0;
function Render(){

   //This will likely be expanded in the future to take elements from the Schema.
    
    var ListToRender = ObtainRenderList();
    RenderBox = document.getElementById('RenderContent');
    //alertToMonitor("RenderThis: "+RenderProperties.RenderList);
    //Generate table body and headder.
    RenderBox.innerHTML = "";
    if( RenderBox.childNodes ){
	for( var i=0;i<RenderBox.childNodes.length;i++){
	    RenderBox.removeChild( RenderBox.childNodes[i] );
	}
    }

    NewRenderBoxWidth = RenderBox.clientWidgth;
    NewRenderBoxHeight = RenderBox.clientHeight;
    //Switch between rendering options.
    tagTreeMethod=returnTagTreeMethod();
    if( tagTreeMethod == 'AsTableColumn') {
	TableInBox = document.createElement('table');
	TableInBox.className="sortable";
	TableInBox.border = 2;
	Body = document.createElement('tbody');
	HeadRow=RenderHead(ListToRender);
	Body.appendChild(HeadRow);
	//Plug new table into RenderBox
	TableInBox.appendChild(Body);
	RenderBox.appendChild(TableInBox);
	
	sorttable.makeSortable(TableInBox);

	for(var i=0; i<RunArray.length; i++){
	    //alertToMonitor('run index '+i);
	    RunRow=RenderRun(RunArray[i],ListToRender);
	    Body.appendChild(RunRow);
	}

	NewRenderBoxWidth = TableInBox.clientWidth+3;
	NewRenderBoxHeight = TableInBox.clientHeight + TableInBox.offsetTop+3;

    }else if( tagTreeMethod == 'TreeMethod1') {
	new_size = RenderTagTree1(ListToRender);
	NewRenderBoxLeft = new_size[0];
	NewRenderBoxHeight= new_size[1];
    }else{
	alertToMonitor('Undefined TagTreeMethod: '+tagTreeMethod);
    }
    

    //For some reason, this needs to be done twice or it won't render properly.

      
      NewRenderBoxHeight = 300;
      NewRenderBoxWidth = 300;
      for(var i=0;i<2;i++){
      resizeBox('RenderBox', NewRenderBoxHeight, NewRenderBoxWidth);
      }
      tableResize('RenderBox');
      tableResize('RenderBox');
}
//Examine box contents for dimension.  
var MaxRight = 0;
var MaxBottom = 0;
function tableResize(BoxName){
    boxToAlter = document.getElementById(BoxName);
    if( ! boxToAlter ) {
	alertToMonitor('autoResize: no box found '+ BoxName);
    }
    tableResizeDecender(boxToAlter);
    boxToAlter.style.height = MaxRight;
    boxToAlter.style.width = MaxBottom;
    
}

function tableResizeDecender(element){
    for(var i=0;i<element.childNodes.length;i++){
	child = element.childNodes[i];
	if( child.nodeType != 1 ) continue;
	if( child.nodeName == "TABLE"){
	    //alertToMonitor('kida '+i+ ' w ' + child.clientWidth + ' h '+child.clientHeight);
	    var thisRight =  child.offsetLeft + child.clientWidth;
	    var thisBottom = child.offsetTop + child.clientHeight;
	    MaxRight = ( (MaxRight > thisRight ) ? MaxRight : thisRight );
	    MaxBottom = ((MaxBottom> thisBottom) ? MaxBottom: thisBottom);
	    //alertToMonitor(child.nodeName + " " + thisRight + " " + thisBottom);
	}
	tableResizeDecender(child);

    }    
}

function resizeBox(BoxName, height,width){
    //alertToMonitor("new size: "+ newHeight + " " + newWidth);
    boxToAlter = document.getElementById(BoxName);
    if( ! boxToAlter ) {
	alertToMonitor('resizeBox: no box found '+ BoxName);
    }
    
    boxToAlter.style.height = height;
    boxToAlter.style.width = width;
}

function RenderHead(ListToRender){
    HeadRow = document.createElement('tr');
    for(var i=0; i<ListToRender.length; i++){
	headItem = document.createElement('th');
	text = document.createTextNode(ListToRender[i].TagName);
	headItem.appendChild(text);
	HeadRow.appendChild(headItem);
    }
    return HeadRow
}    

function determineRenderStyle(element){
    //This needs to be fleshed out more
}
function RenderRun(Run_arg,ListToRender){
    //Needs Error and Exception Handling.
    thisRow = document.createElement('tr');
    for(var w = 0; w<ListToRender.length;w++){


	if( ListToRender[w].RenderMethod != 'Derived'){
	    if( ListToRender[w].RenderMethod == 'Simple'){
		cell = GenerateCellSimple(Run_arg, ListToRender[w]);
	    }else if ( ListToRender[w].RenderMethod == 'SubTable'){
		cell = GenerateCellWithTable(Run_arg, ListToRender[w]);
	    }
	}else{
	    alertToMonitor('NoDerivedMethods yet');
	}

	//For other, more complicated styles, we'll insert them here.


	thisRow.appendChild(cell);

    }
    return thisRow;
}
var counter = 0;
function GenerateCellWithTable(Run_arg, ElementToRender){
    var element = Run_arg.xml.getElementsByTagName(ElementToRender.TagName);

    cell = document.createElement('td');
    var Error = false;
    if( ! element[0] ){ //|| ! element[0].firstChild || ! element[0].firstChild.data){
	Error = true;
    }

    if( ElementToRender.funcArgs ){
	if( ElementToRender.funcArgs.TagName ){
	    TagName = ElementToRender.funcArgs.TagName;
	}else{
	    alert('not quite');
	    Error = true;
	}
	if( ElementToRender.funcArgs.TagAttr ){
	    TagAttr = ElementToRender.funcArgs.TagAttr;
	}else{
	    TagAttr = null;
	}
    }else{
	Error = true;
    }
    if( Error == true   ){ //|| ! element[0].firstChild || ! element[0].firstChild.data){
	text = document.createTextNode( "Testing " + counter );
	cell.appendChild(text);
	
    }else{
	var list_elements = element[0].getElementsByTagName(TagName);
	if( list_elements ){
	    sub_table = document.createElement('table');
	    sub_body = document.createElement('tBod');
	    
	    for( var eee=0;eee<list_elements.length; eee++){
		if( list_elements[eee].firstChild ){

		    some_text = list_elements[eee].firstChild.data;
		    sub_row = document.createElement('tr');

		    if( TagAttr ){
			name_value =  list_elements[eee].attributes[TagAttr].firstChild.data;
			name_cell = document.createElement('td');
			name_text = document.createTextNode( name_value );
			name_cell.appendChild(name_text);
			sub_row.appendChild(name_cell);
		    }

		    sub_cell = document.createElement('td');
		    
		    var sub_text = document.createTextNode( some_text);
		    sub_cell.appendChild(sub_text);
		    sub_row.appendChild(sub_cell);
		    sub_body.appendChild(sub_row);
		}//data
	    }//loop
	}//elements
	sub_table.appendChild(sub_body);


	if( ElementToRender.funcArgs.floatTable && ElementToRender.funcArgs.floatTable == true ) {
	//if( true ){

	    //Make floating box, attach to render box

	    table_div = document.createElement('div');
	    table_div.appendChild(sub_table);
	    table_div.style.display = 'none';
	    table_div.className = 'floatingTable';
	    table_div.style.position = 'fixed';
	    table_div.style.top  = 30;
	    table_div.style.left =0;
	    table_div.style.top = 0;
	    RenderBox = document.getElementById('RenderContent');
	    RenderBox.appendChild(table_div);
	    table_div.table = sub_table;

	    //Set up cell to show box.
	    txt_box = document.createElement('i');
	    tmp_txt = document.createTextNode('Click for table');
	    txt_box.appendChild(tmp_txt)
	    cell.appendChild(txt_box);
	    cell.table_div = table_div;
	    cell.onclick = toggleTable;
	    cell.style.cursor  = "pointer";

	}else{
	    cell.appendChild(sub_table);
	}

    }
    counter++;
    return cell;    
}
function OffsetFrom(elem,DestName){
	var newTop =  this.offsetTop;
	var newLeft = this.offsetLeft + this.clientWidth;    
	alertToMonitor("hi " + elem.parentNode );
	if( elem.parentNode )
	    if( elem.parentNode.id != DestName ){
		var output = OffsetFrom(this,DestName);
		newTop += output[0];
		newLeft += output[1];
	    }
	return [newTop,newLeft];
}
function toggleTable(){
    
    table_div = this.table_div;

    if( table_div.style.display == 'none' ){
	var newLeft = this.offsetLeft + this.clientWidth;    
	//alertToMonitor( OffsetFrom(this,'RenderContent') );
	//table_div.style.top = newTop;
	table_div.style.left = newLeft;
	table_div.style.display = 'block';
	pop_table_width = table_div.table.clientWidth;
	pop_table_height =table_div.table.clientHeight;
	table_div.style.width = pop_table_width;
	table_div.style.height = pop_table_height;

	text_in_cell =this.getElementsByTagName('i');
	if( text_in_cell ){
	    text_in_cell[0].childNodes[0].data = "Click to Hide";
	}
	this.style.background = "lightblue";
    }else{
	table_div.style.display = 'none';
	text_in_cell =this.getElementsByTagName('i');
	if( text_in_cell ){
	    text_in_cell[0].childNodes[0].data = "Click for table";
	}
	this.style.background = "white";
    }
}
function GenerateCellSimple(Run_arg, ElementToRender){
    element = Run_arg.xml.getElementsByTagName(ElementToRender.TagName);

    cell = document.createElement('td');

    if( ! element[0] || ! element[0].firstChild || ! element[0].firstChild.data){
	//alertToMonitor("RenderRun: element not found: " + ListToRender[w]);
	text_value = "";
    }else{
	text_value = element[0].firstChild.data;
	cell.runElement = element;
	
	//For redraws, keep track of class information addded to the element.
	if( element[0].hasOwnProperty('className') )
	    cell.className = element[0].className;
	

    }

    text = document.createTextNode(text_value);
    cell.appendChild(text);
    cell.onclick = CellEditor;
    return cell;
}
function Run(){
    this.tagList = new Array();
    this.xml=new Object;
    //will have more things later.
}
Run.prototype.fillTags = function(){
    
    //Clear the tag list, get the tag list from the XML, sort.
    xmlList = this.xml.getElementsByTagName('TagList');
    this.tagList.splice(0,this.tagList.length);
    if( xmlList[0] ){
	var list_elements = xmlList[0].getElementsByTagName("Tag");
	if( list_elements ){
	    for( var eee=0;eee<list_elements.length; eee++){
		if( list_elements[eee].firstChild ){
		    this.tagList.push(list_elements[eee].firstChild.data);
		}
	    }
	}else{
	    this.tagList.push('');	    
	}
    }else{
	this.tagList.push('');
    }
    this.tagList.sort();

}
function RenderPropertiesObject(TagName, TagText,RenderStatus, RenderMethod,funcArgs){

    this.TagName = ( TagName ) ? TagName : "UnNamedTag";
    this.TagText = ( TagText ) ? TagText : TagName;
    this.RenderStatus   = ( RenderStatus ) ? RenderStatus : "No";
    this.RenderMethod =   ( RenderMethod ) ? RenderMethod : "Simple";
    this.funcArgs = ( funcArgs ) ? funcArgs : null;
}
